package com.suke.czx.modules.person.controller;

import java.util.Map;
import java.util.Base64;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.suke.czx.modules.person.entity.TestPerson;
import com.suke.czx.modules.person.service.TestPersonService;
import org.springframework.web.bind.annotation.*;
import com.suke.zhjg.common.autofull.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.EncodeHintType;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.net.URLEncoder;

/**
 * 人员表（GitHub Pages链接版）
 */
@RestController
@AllArgsConstructor
@RequestMapping("/person/person")
@Api(value = "TestPersonController", tags = "人员表")
public class TestPersonController extends AbstractController {
    private final TestPersonService testPersonService;
    private final ObjectMapper objectMapper;

    // GitHub Pages配置（用户需替换为自己的仓库信息）
    private static final String GITHUB_PAGES_URL = "https://chenshuanggithub.github.io/cs.github.io/index.html";

    /**
     * 生成包含人员信息链接的二维码
     */
    @ApiOperation(value = "生成人员二维码")
    @PostMapping("/generateQrCode")
    public R generateQrCode(@RequestBody TestPerson testPerson) {
        try {
            // 1. 生成带参数的GitHub Pages链接
            String personLink = generateGitHubPagesLink(testPerson);

            // 2. 二维码参数配置
            HashMap<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1);

            // 3. 生成二维码
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(personLink, BarcodeFormat.QR_CODE, 400, 400, hints);

            // 4. 输出二维码图片
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
            String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());

            return R.ok()
                    .put("qrCode", "data:image/png;base64," + base64Image)
                    .put("personLink", personLink); // 返回生成的链接，方便测试
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("生成二维码失败: " + e.getMessage());
        }
    }

    /**
     * 生成带参数的GitHub Pages链接
     */
    private String generateGitHubPagesLink(TestPerson person) throws Exception {
        // 构建URL参数
        StringBuilder params = new StringBuilder();
        params.append("?name=").append(URLEncoder.encode(person.getName(), StandardCharsets.UTF_8.name()));
        params.append("&age=").append(person.getAge() != null ? person.getAge() : "");
        params.append("&address=").append(URLEncoder.encode(person.getAdress() != null ? person.getAdress() : "", StandardCharsets.UTF_8.name()));
        params.append("&info=").append(URLEncoder.encode(person.getInfo() != null ? person.getInfo() : "", StandardCharsets.UTF_8.name()));

        // 拼接完整链接
        return GITHUB_PAGES_URL + params.toString();
    }

    // 保留必要的其他接口...
    @GetMapping("/list") public R list(@RequestParam Map<String, Object> params) {
        QueryWrapper<TestPerson> queryWrapper = new QueryWrapper<>();
        String keyword = mpPageConvert.getKeyword(params);
        if (StrUtil.isNotEmpty(keyword)) {}
        IPage<TestPerson> listPage = testPersonService.page(mpPageConvert.<TestPerson>pageParamConvert(params), queryWrapper);
        return R.ok().setData(listPage);
    }

    @PostMapping("/save") public R save(@RequestBody TestPerson testPerson) {
        testPersonService.save(testPerson);
        return R.ok().setData(testPerson);
    }

    @PostMapping("/update") public R update(@RequestBody TestPerson testPerson) {
        testPersonService.updateById(testPerson);
        return R.ok();
    }

    @DeleteMapping("/delete") public R delete(@RequestBody TestPerson testPerson) {
        testPersonService.removeById(testPerson.getId());
        return R.ok();
    }
}